package com.atguigu.gulimall.client.controller;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
public class HelloController {

    @Value("${sso.server.url}")
    String ssoServerUrl;

    /**
     * 无需登录
     * @return
     */
    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        return "hello";
    }

    /**
     * 需要登录
     * 需要知道ssoserver登录成功后回来
     * @return
     */
    @GetMapping("/employees")
    public String employees(Model model, HttpSession session,
                           @RequestParam(value = "token",required = false) String token){

        if (!StringUtils.isEmpty(token)){
            //去ssoserver登录成功会带上token
            //TODU:拿到token后，还要去ssoservice获取token对应的用户信息
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> forEntity = restTemplate.getForEntity("http://eureka7001.com:8080/userInfo?token=" + token, String.class);
            String body = forEntity.getBody();
            session.setAttribute("loginUser",body);
        }
        Object loginUser = session.getAttribute("loginUser");
        if (loginUser == null){
            return "redirect:"+ssoServerUrl+"?redirect_url=http://eureka7002.com:8081/employees";
        }

        List<Object> employees = new ArrayList<>();
        employees.add("wxxu");
        employees.add("yangnyuanfang");

        model.addAttribute("emps",employees);
        return "list";
    }
}
